<?php
class routeAction extends commonAction{
    private $ActionList = array(
        "archive/index" => "内容页模块",
        "arctype/index" => "列表页模块"
    );
    /*
    $optionsM=D('Options');
    $optionsM_re=$optionsM->getByOptionName("RouteUrlRule");//从配置表中读取url规则参数
    $RouteUrlRule=$optionsM_re['option_value'];
    if($RouteUrlRule){
        $RouteUrlRule=unserialize($RouteUrlRule);//反序列化成数组
    }
    if(!is_array($RouteUrlRule)){
        $RouteUrlRule=array();//如果反序列失败则强制设置为空数组
    }

    $this->assign("rules",$RouteUrlRule);
    $this->display();
     */
    //url规则设置
    function index(){
        redirect(U("urlrule"));//跳转到url规则列表
        
    }
    
    //url规则列表
    function urlrule(){
        $urlruleM=D('Urlrule');//实例化url规则表模型
        $rulelist=$urlruleM->select();//取出所有url规则
        $this->assign("rulelist",$rulelist);
        $this->display();
    }
    
    //添加一个url规则
    function addurlrule(){
        if(!$this->isPost()){
            $this->assign("ActionList",$this->ActionList);
            $this->display();
        }else{
            $urlruleM=D('Urlrule');//实例化规则表模型
            $action=I("action");
            $rule=I("rule");
            if(!$action || !$rule){
                $this->error("请选择模块并填写规则");
            }
            if(!isset($this->ActionList[$action])){
                $this->error("不支持这个模块哦！~");
            }
            if($urlruleM->getByAction($action)){
                $this->error("改模块的规则已经存在，请不要重复添加");
            }
            if($urlruleM->create()){
                if($urlruleM->add()){
                    F("UrlRule",NULL);//删除缓存
                    $this->success("规则创建成功，请及时更新路由规则");
                }else{
                    $this->error($urlruleM->getDbError());
                }
            }else{
                $this->error($urlruleM->getError());
            }
        }
    }
    //编辑一个url规则
    function editurlrule(){
        $urlruleM=D('Urlrule');//实例化规则表模型
        if(!$this->isPost()){
            $id=I("id");
            $ruleinfo=$urlruleM->getById($id);//查询规则信息
            $this->assign("ActionList",$this->ActionList);
            $this->assign("ruleinfo",$ruleinfo);
            $this->display();
        }else{
            $action=I("action");
            $rule=I("rule");
            $id=I("id");
            if(!isset($this->ActionList[$action])){
                $this->error("不支持这个模块哦！~");
            }
            if($urlruleM->create()){
                if(FALSE!==$urlruleM->save()){
                    F("UrlRule",NULL);//删除缓存
                    $this->success("规则保存成功，请及时更新路由规则");
                }else{
                    $this->error($urlruleM->getDbError());
                }
            }else{
                $this->error($urlruleM->getError());
            }
        }
    }
    //删除url规则
    function deleteurlrule(){
        $id=I("id");
        if(!is_numeric($id)){
            $this->error("id不合法");
        }
        $urlruleM=D('Urlrule');
        if(FALSE!==$urlruleM->where("id='{$id}'")->delete()){
            $this->success("删除成功，请及时更新路由规则");
        }else{
            $this->error("错误：".$urlruleM->getDbError());
        }
    }
    
    
    //路由规则设置
    function route(){
        if(!$this->isPost()){
            $routes=include APP_PATH.'Conf/routeconf.php';//加载路由配置文件，读取配置
            $RouteRules=  isset($routes['cms_urlrules'])?$routes['cms_urlrules']:array();
            $RouteRulesStr="";
            foreach($RouteRules as $k=>$v){
                $RouteRulesStr.=$k."=>".$v."\n";
            }
            $this->assign("RouteRulesStr",$RouteRulesStr);
            $this->display();
        }else{
            $RouteRules=trim($_POST["RouteRules"]);
            $Rules=array_filter(explode("\n",$RouteRules));
            $routes=array();
            foreach($Rules as $eachrule){
                list($k,$v)=explode("=>",$eachrule);
                $routes['cms_urlrules'][trim($k)]=trim($v);
            }
            $RoutesStr="<?php\nreturn ".stripslashes(var_export($routes,TRUE)).';';
            file_put_contents(APP_PATH.'Conf/routeconf.php', $RoutesStr);
            
            $this->success("保存成功");
        }
    }
    
    /*
    //保存路由规则
    function save(){
        $options=array();//参数数组，用于保存到数据库
        
        $arcrule=I("post.arcrule","");//文章规则无分页
        $arcrule1=I("post.arcrule1","");//文章规则有分页
        $typerule=I("post.typerule","");//分类规则无分页
        $typerule1=I("post.typerule1","");//分类规则有分页
        $options=compact("arcrule","arcrule1","typerule","typerule1");
        $route_rule=array();//路由规则初始化
        $route_rule["cms_urlrules"]=array();
        $this->_parseArcRule($arcrule1,$route_rule);//生成文档页路由规则
        $this->_parseArcRule($arcrule,$route_rule);//生成文档页路由规则
        $this->_parseTypeRule($typerule1,$route_rule);//生成分类路由规则
        $this->_parseTypeRule($typerule,$route_rule);//分类默认首页规则生成
        
        //写入option表
        $this->_save2option($options);
        
        //写入配置文件
        $this->_save2conf($route_rule);
        
        $this->success("URL设置成功");
    }
    
    private function _parseArcRule($rule="",&$route){
        $querystring="";//路由规则右侧查询参数
        if($rule==""){
            return true;//如果规则为空则直接返回
        }
        preg_match_all("/[a-z]+#/i",$rule,$m);//从规则字符串中匹配出所有通配符
        
        $aidkey=$pkey=$typeidkey=$typealiakey=0;//初始化各通配符对应正则子组序号
        foreach($m[0] as $k=>$v){
            if($v=="id#" && $aidkey==0){
                $aidkey=$k+1;
                $querystring.=$querystring==""?"aid=:{$aidkey}":"&aid=:{$aidkey}";
            }
            if($v=="p#" && $pkey==0){
                $pkey=$k+1;
                $querystring.=$querystring==""?"p=:{$pkey}":"&p=:{$pkey}";
            }
            if($v=="typeid#" && $typeidkey==0){
                $typeidkey=$k+1;
                $querystring.=$querystring==""?"typeid=:{$typeidkey}":"&typeid=:{$typeidkey}";
            }
            if($v=="typealia#" && $typealiakey==0){
                $typealiakey=$k+1;
                $querystring.=$querystring==""?"typealia=:{$typealiakey}":"&typealia=:{$typealiakey}";
            }
        }
        if($aidkey==0){
            $this->error("文档URL规则必须包含#id#");
        }
        $rule=preg_quote($rule,"/");
        $rule=preg_replace('/#([^#]*)p#/i','${1}(\\d+)',$rule);
        $rule=str_replace(array("#year#","#month#","#day#","#typeid#","#id#"),'(\d+)',$rule);//数字类型字段
        $rule=str_replace('#typealia#','(\S+)',$rule);//字符串类型字段,非空白字符
        $rule=preg_replace('/#.*?#/i','',$rule);//过滤非法通配符
        $rule='/'.$rule.'/';
        $route["cms_urlrules"][$rule]="archive/index?".$querystring;
        
        return true;
    }
    private function _parseTypeRule($rule="",&$route){
        $querystring="";//路由规则右侧查询参数
        if($rule==""){
            return true;//如果规则为空则直接返回
        }
        preg_match_all("/[a-z]+#/i",$rule,$m);//从规则字符串中匹配出所有通配符
        
        $pkey=$typeidkey=$typealiakey=0;//初始化各通配符对应正则子组序号
        foreach($m[0] as $k=>$v){
            
            if($v=="p#" && $pkey==0){
                $pkey=$k+1;
                $querystring.=$querystring==""?"p=:{$pkey}":"&p=:{$pkey}";
            }
            if($v=="typeid#" && $typeidkey==0){
                $typeidkey=$k+1;
                $querystring.=$querystring==""?"typeid=:{$typeidkey}":"&typeid=:{$typeidkey}";
            }
            if($v=="typealia#" && $typealiakey==0){
                $typealiakey=$k+1;
                $querystring.=$querystring==""?"typealia=:{$typealiakey}":"&typealia=:{$typealiakey}";
            }
        }
        if($typeidkey==0 && $typealiakey==0){
            $this->error("typeid和typealia至少包含一个");
        }
        $rule=preg_quote($rule,"/");
        $rule=preg_replace('/#([^#]*)p#/i','${1}(\\d+)',$rule);
        $rule=str_replace("#typeid#",'(\d+)',$rule);//数字类型字段
        $rule=str_replace('#typealia#','(\S+)',$rule);//字符串类型字段,非空白字符
        $rule=preg_replace('/#.*?#/i','',$rule);//过滤非法通配符
        $rule='/'.$rule.'/';
        $route["cms_urlrules"][$rule]="arctype/index?".$querystring;
        
        return true;
    }
    
    //写入到option表
    private function _save2option($rule){
        if(!is_array($rule)){
            return false;
        }
        $rule_serialize=serialize($rule);
        $optionsM=D('Options');
        $re=$optionsM->data(array("option_name"=>"RouteUrlRule","option_value"=>$rule_serialize,"option_group"=>"UrlRule"))->add("","",true);//覆盖插入
        if($re===FALSE){
            $this->error($optionsM->getDbError());
        }
        return true;
    }
    //写入到配置文件
    private function _save2conf($route_rule){
        $route_rule_var=stripslashes(var_export($route_rule,true));//将路由设置转换为数组
        $route_rule_var="<?php\nreturn ".$route_rule_var.';';
        file_put_contents(APP_PATH."./Conf/routeconf.php",$route_rule_var);
        return true;
    }
    
    */
}
